<?php
namespace Common\Model;

class SiteModel extends Model {
    protected $tableName = 'site';

    /**
     * buildSearchExpr 
     * 组装查询条件
     * 
     * @param mixed $d  查询数据，一般来源于$_GET或$_POST
     * @param mixed $field  可查询的字段对照表，其结构为array(array('表单项目名称' => '数据库字段名称'))
     * @access public
     * @return void 返回值为数组，参见方法内部注释
     */
    public function buildSearchExpr($d, $field = NULL) {
        $expr = array();
        $dao  = array();
        $sortExpr = $this->pk . ' DESC';

        /**
         * 下标为表单中的项目名称，值为数据库中表的字段名称 
         */
        if (empty($field)) {
            $field = array(
                'uid'    => 'uid',
                'id'     => 'id',
                'domain' => 'domain',
                'status' => 'status',
            );
        }

        foreach($field as $k => $v) {
            $val = isset($d[$k]) ? trim($d[$k]) : '';

            if (strlen($val) < 1) {
                continue;
            }

            switch($k) {
                case 'domain' :
                case 'status' :

                default:
                    $expr[$v] = $val;
            }

            $dao[$k] = $d[$k];
        }

        /**
         * 处理多个查询项目合并到一起，然后只能选一项查询的情况
         * 保存到$dao中，用于回填至查询表单
         */
        foreach($d as $k => $v) {
            if(substr($k, 0, 12) == 'search_item_') {
                $dao[$k] = $v;
            }
        }

        /**
         * 因为部分查询会涉及到视图，所以需要在下面指定完整的可排序字段
         */
        $sortField = array('id', 'uid');

        if(!empty($d['sort']) && in_array($d['sort'], $sortField)) {
            $sortdir = empty($d['sortdir'])                     ? 'DESC'   : strtoupper($d['sortdir']);
            $sortdir = in_array($sortdir, array('DESC', 'ASC')) ? $sortdir : 'DESC';

            $sort     = $d['sort'];
            $sortExpr = "{$sort} {$sortdir}";

            $dao['sort']    = $sort;
            $dao['sortdir'] = $sortdir;
        }

        return array(
            'expr' => $expr,            //ThinkPHP查询条件表达式
            'sort' => $sortExpr,        //排序表达式
            'json' => json_encode($dao) //用于回填至查询表单的数据
        );
    }

    public function save2($d) {
        $id     = empty($d['id']) ? 0 : (int)$d['id'];
        $action = 'save';

        if (empty($d['domain'])) {
            throw new \Exception('请指定域名');
        }

        if ($this->checkDomainExists($d['domain'], $id)) {
            throw new \Exception('域名已经存在');
        }

        if (empty($id)) {
            $uid    = empty($d['uid']) ? 0 : (int)$d['uid'];
            $action = 'add';

            if (empty($uid)) {
                throw new \Exception('请确认网站所属的站长');
            }

            if (!D('Siter')->getById($uid)) {
                throw new \Exception('未找到站长数据');
            }

            $d['create_time'] = date('Y-m-d H:i:s');
        } else {
            if (!$record = $this->where(['id' => $id])->find()) {
                throw new \Exception('没有找到网站数据');
            }
        }

        /**
         * add时为何没返回新增的id
         */
        if ($action == 'add') {
            $r  = $this->add($d);
            $id = $r;
        } else {
            unset($d['id']);
            $r = $this->where(['id' => $id])->save($d);
        }

        try {
            cacheApi('site', [
                'a'  => ($action == 'add' ? 'add' : 'modify'),
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    /**
     * checkDomainExists
     * 检测域名是否已经存在
     *
     * @param mixed $domain
     * @param mixed $excludeId
     * @return void
     */
    public function checkDomainExists($domain, $excludeId = null) {
        $excludeId = (int)$excludeId;
        $expr      = ['domain' => $domain];

        if (!empty($excludeId)) {
            $expr['id'] = ['NEQ', $excludeId];
        }

        return $this->where($expr)->find() ? true : false;
    }


    /**
     * del
     *
     * @param mixed $id
     * @return void
     */
    public function del($id) {
        $id = (int)$id;

        if (!$record = $this->where(['id' => $id])->find()) {
            return true;
        }

        try {
            cacheApi('site', [
                'a'  => 'del',
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        $expr = ['id' => $id];
        $this->where($expr)->delete();

        return true;
    }

    /*
    protected function _before_update(&$data, &$options) {
        if(!isset($data[$this->getPk()])) {
            return false;
        }

        if(isset($options['where']) && !array_key_exists($this->getPk(), $options['where'])) {
            $options['where'][$this->getPk()] = $data[$this->getPk()];
        }

        return true;
    }
     */

    /*
    protected function _options_filter(&$options) {
        if(!$loginUser = C('RUN_LOGIN_USER')) {
            exit('NO LOGIN');
        }

        if($loginUser['type'] == 1) {
            $options['where']        = isset($options['where']) ? $options['where'] : array();
            $options['where']['uid'] = $loginUser['uid'];

            return true;
        }
    }
     */

}
